package com.qding.park.manager.service.statis.biz;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.qding.park.common.utils.ListUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.pojo.TbCar;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbUserInfo;
import com.qding.park.manager.pojo.ap.ApUserCarInfo;
import com.qding.park.manager.pojo.enums.CardStatuEnum;
import com.qding.park.manager.pojo.enums.UserTypeEnum;
import com.qding.park.manager.service.statis.mapper.TbCarStatisMapper;
import com.qding.park.manager.service.statis.mapper.TbParkspaceStatisMapper;
import com.qding.park.manager.service.statis.mapper.TbSupplycomanyStatisMapper;
import com.qding.park.manager.service.statis.mapper.TbUserInfoStatisMapper;

/**
 * @ClassName CarBiz
 * @Description TODO(与车辆有关的业务)
 * @author Administrator
 * @Date 2016年8月25日 上午10:13:18
 * @version 1.0.0
 * 
 * 
 */
@Component("carStatisBiz_statis")
public class CarStatisBiz {

	private static final Log _log = LogFactory.getLog(CarStatisBiz.class);

	@Autowired
	private TbParkspaceStatisMapper tbParkspaceMapper;

	@Autowired
	private TbUserInfoStatisMapper tbUserInfoMapper;

	@Autowired
	private TbCarStatisMapper tbCarMapper;

	@Autowired
	private TbSupplycomanyStatisMapper tbSupplycomanyMapper;

	@Autowired
	private AdapterParkProxyFactory adapterParkProxyFactory;

	@Autowired
	private UserDBAtomic userDBAtomic;
	
	@Autowired
	private  ParkCacheInter  parkCacheInter;

	





//	public void userCarInfoSync(int parkId) throws BaseException {
//
//		TbParkspace tbParkspace=parkCacheInter.queryParkSpace(parkId);
//		if (tbParkspace == null) {
//			_log.info("车场列表为空，同步任务已完成");
//			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
//					ExceptionMessage.createExceptionMessage(
//							ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "无此车场", " 车牌=" + parkId));
//		}
//
//		_log.info("同步车场的用户数据 size=" + 1);
//
//		String parkCode = tbParkspace.getParkCode();
//		int supplierId = tbParkspace.getSupplierId();
//		AdapterProxy adapterProxy = adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
//
//		List<ApUserCarInfo> apusercarList = adapterProxy.getCarAdapter().allUserCar(parkCode);
//
//		syncUser(apusercarList);
//		syncUsercaReleation(apusercarList, tbParkspace);
//	}

	private long  tel2Long(String str){
	    
	    long tel=-1L;
	    
	    try{
	        tel=Long.valueOf(str);
	    }catch(Exception e){
	        _log.error(e, e);
	    }
	    return tel;
	}
	
	/**
	 * syncUser(同步用户信息) TODO(这里描述这个方法适用条件 – 可选) TODO(这里描述这个方法的执行流程 – 可选)
	 * TODO(这里描述这个方法的使用方法 – 可选) TODO(这里描述这个方法的注意事项 – 可选) @Title:
	 * syncUser @Description: TODO @param @param apusercarList 设定文件 @return void
	 * 返回类型 @throws
	 */
//	@Transactional(rollbackFor = Throwable.class)
	private void syncUser(List<ApUserCarInfo> apusercarList) {
		List<TbUserInfo> tbuserList = new ArrayList<TbUserInfo>();

		Set<String> tagSet = new HashSet<String>();
		if (!ListUtil.isEmpty(apusercarList)) {
			for (ApUserCarInfo ap : apusercarList) {

				String tels = ap.getContact_Tel1();
				String name = ap.getMember_Name();
				String carNum = ap.getCarNumber();
				String homeAddr=ap.getHome_Address();
				String[] telArray = tels.split(",");
				for (String t : telArray) {
					if (StringUtils.isBlank(t) || tagSet.contains(t)) {
						continue;
					}
					TbUserInfo u = new TbUserInfo();
//					u.setTel(Long.valueOf(t.trim()));
					u.setTel(tel2Long(t));
					tbuserList.add(u);
					u.setName(name);
					u.setHomeAddr(homeAddr);

					tagSet.add(t);
				}
			}

			for (TbUserInfo userInfo : tbuserList) {
				// TbUserInfo u =
				// tbUserInfoMapper.queryUserByTel(userInfo.getTel());
				userInfo.setUserType(UserTypeEnum.REGISTER_USER.getType());
//				if(userInfo.getName().equals("雷阳")){
//					System.out.println("dd");
//				}
				int num = tbUserInfoMapper.update(userInfo);

//				if (num == 0) {
					// userDBAtomic.saveUserAtomicTelNotExists(userInfo);
					userInfo.setUserType(UserTypeEnum.REGISTER_USER.getType());
					userDBAtomic.register_loginUser(userInfo);
//				}
				// if (u == null) {
				// tbUserInfoMapper.save(userInfo);
				//// tbUserInfoMapper.insertnotExistis(userInfo);
				// }else{
				// u.setUserType(UserTypeEnum.REGISTER_USER.getType());
				// tbUserInfoMapper.update(u);
				// }

			}
			// tbUserInfoMapper.batchInsert(tbuserList);
		}

	}

	/**
	 * syncUsercaReleation(同步用户登记车牌信息) TODO(这里描述这个方法适用条件 – 可选)
	 * TODO(这里描述这个方法的执行流程 – 可选) TODO(这里描述这个方法的使用方法 – 可选) TODO(这里描述这个方法的注意事项 –
	 * 可选)
	 *
	 * @Title: syncUsercaReleation @Description: TODO @param @param
	 *         apusercarList 设定文件 @return void 返回类型 @throws
	 */
//	@Transactional(rollbackFor = Exception.class)
	private void syncUsercaReleation(List<ApUserCarInfo> apusercarList, TbParkspace park) {
		int parkId = park.getId();
		int supplierId = park.getSupplierId();
		String parkName = park.getName();
		List<TbCar> tbusercarList = new ArrayList<TbCar>();
		List<TbCar> tbcarhas = tbCarMapper.listByParkid(parkId);
		Set<String> car_carnum_userid = new HashSet<String>();
		Set<String> car_carnum_userid_new = new HashSet<String>();
		for (ApUserCarInfo ap : apusercarList) {
			String tels = ap.getContact_Tel1();
			String[] telArray = tels.split(",");
			for (String t : telArray) {
				if (StringUtils.isBlank(t)) {
					continue;
				}
				TbUserInfo tbuserinfo = tbUserInfoMapper.queryUserByTel(tel2Long(t));
				if(tbuserinfo==null){
					continue;
				}
				int userid = tbuserinfo.getId();
				String carNum = ap.getCarNumber();
				int cardType = ap.getCardType();
				int cardState = ap.getCardState();
				int carType=ap.getCarType();
				int monthFee=ap.getMonthFee();
				String operator=ap.getRequireguy();//操作员
				String carSpace=ap.getCarpos();//车位
				Date issueTime=ap.getRequiretime();//发行时间
				String memeberName=ap.getMember_Name();
				Date expireDate = ap.getExpireDate();
				String cardName=ap.getCardDescript();

				TbCar car = new TbCar();
				car.setParkID(parkId);
				car.setSupplierId(supplierId);
				car.setParkName(parkName);
				car.setUserID(userid);
				car.setCarNum(carNum);
				car.setStatus(cardState);
				car.setCardType(cardType);
				car.setCardExpiration(expireDate);
				car.setCarType(carType);
				car.setMonthFee(monthFee);
				car.setMemberName(memeberName);
				car.setCarSpace(carSpace);
				car.setIssueTime(issueTime);
				car.setOperator(operator);
				car.setCardName(cardName);
				tbusercarList.add(car);
			}

		}

		List<TbCar> inserts = new ArrayList<TbCar>();
		List<TbCar> updates = new ArrayList<TbCar>();
		List<TbCar> dels = new ArrayList<TbCar>();

		for (TbCar car : tbcarhas) {
			car_carnum_userid.add(parkId + ":" + car.getCarNum() + ":" + car.getUserID());
		}

		for (TbCar car : tbusercarList) {
			car_carnum_userid_new.add(parkId + ":" + car.getCarNum() + ":" + car.getUserID());
		}

		for (TbCar car : tbusercarList) {
			String tag = park.getId() + ":" + car.getCarNum() + ":" + car.getUserID();
			if (car_carnum_userid.contains(tag)) {
				updates.add(car);
			} else {
				// car.setId(tbCarMapper.getNextValue());
				inserts.add(car);
			}
		}

		for (TbCar car : tbcarhas) {
			String tag = park.getId() + ":" + car.getCarNum() + ":" + car.getUserID();
			if (!car_carnum_userid_new.contains(tag)) {
				car.setStatus(CardStatuEnum.DELETED_STATUS.getStatus());
				dels.add(car);
			}
		}

		// tbCarMapper.batchUpdate(tbusercarList);

		if (!ListUtil.isEmpty(updates)) {
			tbCarMapper.batchUpdate(updates);
			// for(TbCar car:updates){
			// tbCarMapper.updateExists(car);
			// }
		}
		if (!ListUtil.isEmpty(inserts)) {
			// tbCarMapper.batchInsert(inserts);
			for (TbCar car : inserts) {
				tbCarMapper.insetNoExists(car);
			}

		}
		if (!ListUtil.isEmpty(dels)) {
			tbCarMapper.batchUpdate(dels);
		}
		
		tbusercarList.clear();
		tbusercarList=null;
		inserts.clear();
		inserts=null;
		updates.clear();
		updates=null;
		dels.clear();
		dels=null;
		
	}


}
